package com.jindianjichi.oss.util;

import com.jindianjichi.oss.entity.FileInfo;
import io.minio.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * minio文件操作工具
 */
@Component
public class MinoUtil {
    @Resource
    private MinioClient minioClient;
    /**
     * 创造桶操作
     */
    public void createBucket(String bucket) throws Exception {
        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!bucketExists){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
        }
    }

    /**
     * 上传文件
     */
    public void uploadFile(InputStream inputStream,String bucket,String objectName) throws Exception {
      // 将输入流包装为BufferedInputStream以支持mark/reset
      InputStream bufferedStream = new java.io.BufferedInputStream(inputStream);
      minioClient.putObject(PutObjectArgs.builder().bucket(bucket).object(objectName)
              .stream(bufferedStream, bufferedStream.available(), -1).build());
    }

    /**
     * 列出所有的桶
     */
    public List<String> getAllBucket() throws Exception {
        List<Bucket> buckets = minioClient.listBuckets();
        return buckets.stream().map(Bucket::name).collect(Collectors.toList());
    }

    /**
     * 列出当前桶的所以文件
     */
    public List<FileInfo> getAllFiles(String bucket) throws Exception {
        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucket).build());
        List<FileInfo> fileInfoList=new ArrayList<>();
        for (Result<Item> result : results) {
            FileInfo fileInfo=new FileInfo();
            Item item = result.get();
            fileInfo.setFileName(item.objectName());
            fileInfo.setEtag(item.etag());
            fileInfo.setDirectoryFlag(item.isDir());
            fileInfoList.add(fileInfo);
        }

        return fileInfoList;
    }
    /**
     * 下载文件
     */
    public InputStream download(String bucket, String objectName) throws Exception {
       return minioClient.getObject(
                GetObjectArgs.builder().bucket(bucket).object(objectName).build()
        );
    }
    /**
     * 删除桶
     */
    public void deleteBucket(String bucket) throws Exception {
        minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucket).build());
    }

    /**
     * 删除文件
     */
    public void deleteObjects(String bucket, String objectName) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(objectName).build());
    }
}
